#!/usr/bin/ruby
# encoding: utf-8

####################################################################################################
################################### establish project environment ##################################
####################################################################################################
load './config/antlr3.rb'

#rake = Rake.application
#def rake.standard_exception_handling
#  begin
#    yield
#  rescue SystemExit => ex
#    raise
#  rescue OptionParser::InvalidOption => ex
#    exit( false )
#  rescue Exception => ex
#    $stderr.puts( '=' * 80 )
#    $stderr.puts( "#{ name } aborted!" )
#    $stderr.puts( "#{ ex.class }: #{ ex.message }" )
#    $stderr.puts( '-' * 80 )
#    for trace in ex.backtrace
#      $stderr.puts( "  - #{ trace }" )
#    end
#    exit( false )
#  end
#end

def run_task( name )
  Rake::Task.task_defined?( name ) or file( name )
  case task = Rake::Task[ name ]
  when Rake::FileTask then task.needed? and task.invoke
  else task.invoke
  end
end

def abs( path ); File.expand_path( path ); end

def rel( target, reference = Dir.pwd )
  pair = [ target, reference ].map! do |path|
    File.expand_path( path.to_s ).split( File::Separator ).tap do |list|
      if list.empty? then list << String.new( File::Separator )
      elsif list.first.empty? then list.first.replace( File::Separator )
      end
    end
  end

  target_list, reference_list = pair
  while target_list.first == reference_list.first
    target_list.shift
    reference_list.shift or break
  end
  
  relative_list = Array.new( reference_list.length, '..' )
  relative_list.empty? and relative_list << '.'
  relative_list.concat( target_list ).compact!
  return relative_list.join( File::Separator )
end


####################################################################################################
######################################### task definitions #########################################
####################################################################################################

# tasks concerning the development environment
task :update do
  $project.load_task 'update_gems'
end

desc "setup project development environment and download/update bundled gems"
task :boot => %w( update ) do
  $project.load_environment
end

# tasks concerning the ANTLR java package
desc "update the antlr jar if necessary"
task :antlr do
  $project.load_task 'antlr'
end

for task_lib in %w( notes package coverage publish test doc )
  $project.load_task( task_lib )
end

desc( "clean up all project by-products" )
task :clean => %w( test:clean package:clobber doc:clobber doc:samples:clobber )

$project.load_task( 'private/*' )
